const enterpriseVue = new Vue({
  el: '#app',
  data() {
    return {
      pickerOptions: pickerOptions,
      rules: {
        Start_Date: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
        End_Date: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
        // ShopColumn_Id: [{ required: true, message: '请选择栏目', trigger: 'blur' }],
      },
      Article_SerialNumber: [{ required: true, message: '请选择商品', trigger: 'change' }],
      Specifications_Name: [{ required: true, message: '请选择规格', trigger: 'change' }],
      Distribute: [{ required: true, message: '请输入分配数量', trigger: 'blur' }],
      Sales_Unit_Price: [{ required: true, message: '请输入销售单价', trigger: 'blur' }],
      store: [],
      column: [],
      shop: [],
      specs: [],
      isDisabled: true,
      type: '',
      //导入属性
      fileList: [],
      sales_unitprice: [],
      Store_SerialNumber: [],
      Start_Date: '',
      End_Date: '',
      Distribute: '',
      Enterprise: [],
      dialogVisible: false,
      always: '00:00:00',
      form: {     //销售价格单
        Sales_Unit_Price_SerialNumber: "",
        Start_Date: '',
        End_Date: '',
        Column_Type: '',
        Row_Status: '2',
        Enterprise_Info_SerialNumber: $.cookie("enterprise"),
        Children: {
          sales_unitprice_detail: [{     //销售价格单明细
            Sales_Unit_Price_Detail_SerialNumber: "",
            Sales_Unit_Price_SerialNumber: '',
            Article_Specifications_SerialNumber: '',
            Article_SerialNumber: '',
            Unit_Price: '',
            Sales_Unit_Price: '',
            Sign: '无货货主',
            Distribute: '',
            Net_Content: '',
            specs: [],
            Children: {
              sales_unitprice_stock: []
            }
          }],
          sales_unitprice_storescope: [{     //销售价格单适用店铺
            Sales_Unit_Price_StoreScope_SerialNumber: "",
            Sales_Unit_Price_SerialNumber: '',
            Store_SerialNumber: '',
          }],
          sales_unitprice_column: [{
            Sales_Unit_Price_Column_SerialNumber: '',
            Sales_Unit_Price_SerialNumber: '', //单价流水号
            ShopColumn_Id: '',  //栏目流水号
            Column_Type: '', //栏目属性
          }]
        }
      },
      loading: false,
      Enterprise_Info_SerialNumber: $.cookie("enterprise")
    }
  },
  mounted() {
    this.getData()
  },
  computed: {
    Column() {
      return function (name) {
        let obj = this.column.filter((item, index) => {
          return name == item.name
        })[0]
        return obj.ShopColumn_Id
      }
    },
    Article() {
      return function (name) {
        let obj = this.shop.filter((item, index) => {
          return name == item.Article_Name
        })[0]
        return obj.Article_SerialNumber
      }
    },
    Unit_Price() {
      return function (name) {
        let obj = this.shop.filter((item, index) => {
          return name == item.Article_Name
        })[0]
        return obj.Unit_Price
      }
    },
    formatTime() {
      return function (time) {
        let d = new Date(time);
        let year = d.getFullYear();
        let month = d.getMonth() + 1
        let day = d.getDate()
        let hour = d.getHours()
        let minute = d.getMinutes()
        let second = d.getSeconds()
        if (month < 10) { month = '0' + month }
        if (day < 10) { day = '0' + day }
        if (hour < 10) { hour = '0' + hour }
        if (minute < 10) { minute = '0' + minute }
        if (second < 10) { second = '0' + second }
        return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
      };
    },
  },
  methods: {
    getData() {
      let _this = this;

      $.ajax({
        type: 'POST',
        url: DomainName + "/getInquiryAction",
        data: {
          Data: "store_info",
          token: $.cookie("token")
        },
        success: function (res) {
          res = res.filter(function (item) {
            return item.Row_Status != '1'
          })
          for (let i = 0; i < res.length; i++) {
            _this.store.push(res[i]);
          }
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
      $.ajax({
        url: DomainName + '/ColumnAll',
        type: 'POST',
        data: { token: $.cookie("token") },
        success: function (res) {
          res = res.filter(function (item) {
            return item.Row_Status != '1'
          })
          for (let i = 0; i < res.length; i++) {
            _this.column.push(res[i]);
          }
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
      $.ajax({
        url: DomainName + '/getArticleInfo2Action',
        type: 'POST',
        data: { token: $.cookie("token") },
        success: function (res) {
          console.log(res)
          res = res.filter(function (item) {
            return item.Row_Status == '0'
          })
          res.forEach(item => {
            item.Article_Name = item.Article_Name + '(所属企业:' + item.Enterprise_Name + ')'
          })
          for (let i = 0; i < res.length; i++) {
            _this.shop.push(res[i]);
          }
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
    },
    validateEnd_Date(rule, value, callback) {
      if (+new Date(value) < +new Date(this.form.Start_Date)) {
        callback(new Error('结算时间不能小于开始时间'));
      } else {
        callback();
      }
    },
    Change_Unit_Price(index) {
      // this.isDisabled = true
      console.log(this.shop[index].Article_SerialNumber);
      let str = this.form.Children.sales_unitprice_detail[index].Article_SerialNumber
      // for (let i = 0; i < this.shop.length; i++) {
      //   if (this.shop[i].Article_SerialNumber == str) {
      //     this.form.Children.sales_unitprice_detail[index].Unit_Price = this.shop[i].Unit_Price
      //   }
      // }
      this.form.Children.sales_unitprice_detail[index].Article_Specifications_SerialNumber = ''
      let _this = this;

      $.ajax({
        type: 'POST',
        url: DomainName + "/SpecificationsIDAction",
        data: {
          Article_SerialNumber: str,
          token: $.cookie("token")
        },
        success: function (res) {
          _this.form.Children.sales_unitprice_detail[index].specs = res
          console.log(res)
          _this.isDisabled = false
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
    },
    Change_Specifications_Name(index) {
      let str = this.form.Children.sales_unitprice_detail[index].Article_Specifications_SerialNumber
      console.log(str)
      console.log(this.form.Children.sales_unitprice_detail[index].specs[0])
      for (let i = 0; i < this.form.Children.sales_unitprice_detail[index].specs.length; i++) {
        console.log(this.form.Children.sales_unitprice_detail[index].specs[i].Article_Specifications_SerialNumber)
        if (this.form.Children.sales_unitprice_detail[index].specs[i].Article_Specifications_SerialNumber == str) {
          this.form.Children.sales_unitprice_detail[index].Net_Content = this.form.Children.sales_unitprice_detail[index].specs[i].Net_Content
          this.form.Children.sales_unitprice_detail[index].Unit_Price = this.form.Children.sales_unitprice_detail[index].specs[i].Unit_Price
        }
      }
    },
    // Change_Column_Type() {
    //   this.column.forEach((item, index) => {
    //     item.options.forEach(item_ => {
    //       if (index == 0 && this.form.ShopColumn_Id == item_.ShopColumn_Id) {
    //         this.form.Column_Type = '0'
    //       } else if (index == 1 && this.form.ShopColumn_Id == item_.ShopColumn_Id) {
    //         this.form.Column_Type = '1'
    //       }
    //     })
    //   })
    // },
    Change_Column_Type() {
      this.column.forEach((item, index) => {
        item.options.forEach(item1 => {
          this.form.Children.sales_unitprice_column.forEach(item2 => {
            if (index == 0 && item2.ShopColumn_Id == item1.ShopColumn_Id) {
              item2.Column_Type = '0'
            } else if (index == 1 && item2.ShopColumn_Id == item1.ShopColumn_Id) {
              item2.Column_Type = '1'
            }
          })
        })
      })
    },
    Automatic(item, Store_SerialNumber, Start_Date, End_Date, time) {
      //一天毫秒数
      let TimeDays = (1000 * 60) * 60 * 24
      if (+new Date(End_Date) <= +new Date(time)) {//若结算时间小于次日补货时间
        item.Children.sales_unitprice_stock.push({
          Sales_Unit_Price_Stock_SerialNumber: "",
          Sales_Unit_Price_Detail_SerialNumber: "",
          Store_SerialNumber,
          Start_Date: Start_Date,
          End_Date: End_Date,
          Distribute: parseInt(item.Distribute),
          Stock_Remain: parseInt(item.Distribute),
          Stock_Sell: 0
        })
      } else {//若结算时间大于次日补货时间
        item.Children.sales_unitprice_stock.push({
          Sales_Unit_Price_Stock_SerialNumber: "",
          Sales_Unit_Price_Detail_SerialNumber: "",
          Store_SerialNumber,
          Start_Date: Start_Date,
          End_Date: this.formatTime(+new Date(time) - 1000),
          Distribute: parseInt(item.Distribute),
          Stock_Remain: parseInt(item.Distribute),
          Stock_Sell: 0
        })
        this.Automatic(item, Store_SerialNumber, time, End_Date, this.formatTime(+new Date(time) + TimeDays))
      }
    },
    submitForm(formName) {
      let _this = this
      //
      console.log(_this.form.Enterprise_Info_SerialNumber)
      console.log(_this.form.Children.sales_unitprice_detail)
      _this.form.Children.sales_unitprice_detail.forEach(item => {
        _this.shop.forEach(item1 => {
          if (item.Article_SerialNumber == item1.Article_SerialNumber) {
            _this.Enterprise.push(item1.Enterprise_Info_SerialNumber);
          }
        })
      })
      _this.Enterprise = _this.Enterprise.filter(item => {
        return item != _this.form.Enterprise_Info_SerialNumber
      })
      let newEnterprise_Info_SerialNumberList = Array.from(new Set(_this.Enterprise))
      console.log(newEnterprise_Info_SerialNumberList);
      // if (_this.form.Children.sales_unitprice_detail[0].Unit_Price == '' || _this.form.Children.sales_unitprice_detail[0].Article_SerialNumber == '' || _this.form.Children.sales_unitprice_detail[0].Sales_Unit_Price == '' || _this.form.Children.sales_unitprice_detail[0].Distribute == '' || _this.form.Children.sales_unitprice_storescope[0].Store_SerialNumber == '') {
      //   return _this.$message.error("请完善信息")
      // }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          _this.loading = true
          //无货货主商品自动按照执行天数，生成货物
          let TimeDays = (1000 * 60) * 60 * 24
          //天数
          // let data = new Date(+new Date(_this.form.End_Date) - +new Date(_this.form.Start_Date)).getDate();
          //1.获取第一次补货时间
          let time = `${_this.form.Start_Date.substring(0, 10)} ${_this.always}`;
          console.log(time)
          console.log(_this.form.Start_Date)
          if (+new Date(time) < +new Date(_this.form.Start_Date)) {
            time = _this.formatTime(+new Date(time) + TimeDays)
          }
          //2.判断结算时间是否小于第一次补货，如果小于等于生成1次库存，开始结束时间与主表相同
          //如果大于，第一次自动生成开始时间到补货时间，第二次自动生成判断剩余时间是否小于24小时，如果小于从补货时间开始，主表结束时间结束
          //如果大于补货时间开始到次日补货时间前1秒结束，第三次自动生成以此类推
          _this.form.Children.sales_unitprice_storescope.forEach(function (item1, index) {
            _this.form.Children.sales_unitprice_detail.forEach(function (item, index) {
              console.log(item)
              if (item.Sign == "无货货主") {
                _this.Automatic(item, item1.Store_SerialNumber, _this.form.Start_Date, _this.form.End_Date, time)
              }
            })
          })
          console.log(_this.form)
          $.ajax({
            url: DomainName + '/getSalesUnitPriceAdd',
            type: 'POST',
            data: {
              Data: JSON.stringify({
                sales_unitprice: [_this.form]
              }),
              Enterprise_Info_SerialNumber: JSON.stringify(newEnterprise_Info_SerialNumberList),
              // E:JSON.stringify(arr),
              token: $.cookie("token")
            },
            success: function (res) {
              if (res.Status === 'success') {
                _this.$message.success("操作成功")
                window.location.href = './SalesUnitprice.html'
              } else {
                _this.$message.error("操作失败，请稍后再试")
              }
            },
            error: function () {
              _this.$message.error("操作失败，请稍后再试")
            },
            complete: function (XMLHttpRequest) {
              _this.loading = false
              if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
              }
            }
          })
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    onExcel() {
      this.dialogVisible = true
    },
    add_sales_unitprice_storescope() {
      this.form.Children.sales_unitprice_storescope.push({     //销售价格单适用店铺
        Sales_Unit_Price_StoreScope_SerialNumber: "",
        Sales_Unit_Price_SerialNumber: '',
        Store_SerialNumber: '',
      })
    },
    remove_sales_unitprice_storescope() {
      if (this.form.Children.sales_unitprice_storescope.length > 1) {
        this.form.Children.sales_unitprice_storescope.pop()
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
    add_sales_unitprice_column() {
      this.form.Children.sales_unitprice_column.push({  //栏目
        Sales_Unit_Price_Column_SerialNumber: '',
        Sales_Unit_Price_SerialNumber: '', //单价流水号
        ShopColumn_Id: '',  //栏目流水号
        Column_Type: '', //栏目属性
      })
    },
    remove_sales_unitprice_column() {
      if (this.form.Children.sales_unitprice_column.length > 1) {
        this.form.Children.sales_unitprice_column.pop()
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
    add_sales_unitprice_detail() {
      this.form.Children.sales_unitprice_detail.push({     //销售价格单明细
        Sales_Unit_Price_Detail_SerialNumber: "",
        Sales_Unit_Price_SerialNumber: '',
        Article_SerialNumber: '',
        Article_Specifications_SerialNumber: '',
        Unit_Price: '',
        Sales_Unit_Price: '',
        Sign: '无货货主',
        Distribute: '',
        Net_Content: '',
        specs: [],
        Children: {
          sales_unitprice_stock: []
        }
      })
    },
    remove_sales_unitprice_detail() {
      if (this.form.Children.sales_unitprice_detail.length > 1) {
        this.form.Children.sales_unitprice_detail.pop()
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
    beforeRemove(file, fileList) {
      this.fileList.pop()
    },
    uploadDetails(file) {
      this.fileList.push({
        name: file.name,
        url: file.type
      })
      let _this = this
      var reader = new FileReader();
      reader.readAsBinaryString(file);
      reader.onload = function (e) {
        var data = e.target.result;
        var wb = XLSX.read(data, {
          type: 'binary' //以二进制的方式读取
        });
        var sheet0 = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
        var str = XLSX.utils.sheet_to_json(sheet0);//利用接口实现转换。
        console.log(str);
        //将整体数据分解成每一条，一条上传一次
        let newArr = []
        //1.将接受到数组便利
        //2.将栏目存到_this.sales_unitprice里并去重
        str.forEach((item, index) => {
          if (newArr.indexOf(item['所属栏目']) == -1) {
            newArr.push(item['所属栏目'])//根据这个数组判断是否重复
            _this.sales_unitprice.push({
              Sales_Unit_Price_SerialNumber: "",
              Start_Date: "",
              End_Date: "",
              ShopColumn_Id: _this.Column(item['所属栏目']),
              Children: {
                sales_unitprice_detail: [],
                sales_unitprice_storescope: []
              }
            })
          }
          //3.将商品等信息添加到对应栏目下的sales_unitprice_detail
          _this.sales_unitprice.forEach((item1, index1) => {
            if (_this.Column(item['所属栏目']) == item1.ShopColumn_Id) {
              item1.Children.sales_unitprice_detail.push({
                Sales_Unit_Price_Detail_SerialNumber: "",
                Sales_Unit_Price_SerialNumber: '',
                Article_SerialNumber: _this.Article(item['商品编号']),
                Unit_Price: _this.Unit_Price(item['商品编号']),
                Sales_Unit_Price: item['销售单价'],
                Sign: item['有/无货货主'],
                Distribute: parseInt(item['分配数量']),
                Children: {
                  sales_unitprice_stock: []
                }
              })
            }
          })
        })
      }
    },
    submitForm1() {
      let _this = this
      _this.loading = true
      //无货货主商品自动按照执行天数，生成货物
      let TimeDays = (1000 * 60) * 60 * 24
      let data = new Date(+new Date(_this.End_Date) - +new Date(_this.Start_Date)).getDate();
      this.sales_unitprice.forEach((item) => {
        //添加时间
        item.Start_Date = _this.Start_Date
        item.End_Date = _this.End_Date
        //添加店铺
        _this.Store_SerialNumber.forEach((item1) => {
          item.Children.sales_unitprice_storescope.push({
            Sales_Unit_Price_StoreScope_SerialNumber: "",
            Sales_Unit_Price_SerialNumber: '',
            Store_SerialNumber: item1,
          })
        })
        //添加库存孙表
        item.Children.sales_unitprice_detail.forEach(function (item1, index) {
          if (item1.Sign == "无货货主") {
            for (let i = 0; i < data; i++) {
              item1.Children.sales_unitprice_stock.push({
                Sales_Unit_Price_Stock_SerialNumber: "",
                Sales_Unit_Price_Detail_SerialNumber: "",
                Execute_Date: _this.formatTime(+new Date(_this.Start_Date) + (i * TimeDays)),
                Distribute: parseInt(item1.Distribute),
                Stock_Remain: parseInt(item1.Distribute),
                Stock_Sell: 0
              })
            }
          }
        })
      })
      console.log(this.sales_unitprice);
      $.ajax({
        url: DomainName + '/GoodsFileAdd',
        type: 'POST',
        data: {
          Data: JSON.stringify({
            sales_unitprice: this.sales_unitprice
          })
        },
        success: function (res) {
          if (res.Status === 'success') {
            _this.$message.success("操作成功")
            window.history.back()
          } else {
            _this.$message.error("操作失败，请稍后再试")
          }
        },
        error: function () {
          _this.$message.error("操作失败，请稍后再试")
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
    }
  }
})